<template>
  <div class="data-management">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="Measurements" name="measurements">
        <div class="measurements-panel">
          <div class="panel-header">
            <h3>Database Measurements</h3>
            <el-button icon="el-icon-refresh" @click="loadMeasurements">Refresh</el-button>
          </div>
          
          <el-table :data="measurements" style="width: 100%">
            <el-table-column prop="_value" label="Measurement Name" />
            <el-table-column label="Actions" width="200">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewFields(scope.row._value)">
                  View Fields
                </el-button>
                <el-button size="mini" @click="viewTags(scope.row._value)">
                  View Tags
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="Write Data" name="write">
        <div class="write-panel">
          <h3>Write Data Point</h3>
          
          <el-form :model="writeForm" label-width="120px">
            <el-form-item label="Measurement" required>
              <el-input v-model="writeForm.measurement" placeholder="e.g., temperature" />
            </el-form-item>
            
            <el-form-item label="Tags">
              <div v-for="(tag, index) in writeForm.tags" :key="'tag-' + index" class="tag-row">
                <el-input v-model="tag.key" placeholder="Tag key" style="width: 45%" />
                <el-input v-model="tag.value" placeholder="Tag value" style="width: 45%" />
                <el-button icon="el-icon-delete" circle size="mini" @click="removeTag(index)" />
              </div>
              <el-button icon="el-icon-plus" size="small" @click="addTag">Add Tag</el-button>
            </el-form-item>
            
            <el-form-item label="Fields" required>
              <div v-for="(field, index) in writeForm.fields" :key="'field-' + index" class="field-row">
                <el-input v-model="field.key" placeholder="Field key" style="width: 35%" />
                <el-input v-model="field.value" placeholder="Field value" style="width: 35%" />
                <el-select v-model="field.type" style="width: 20%">
                  <el-option label="Float" value="float" />
                  <el-option label="Integer" value="integer" />
                  <el-option label="String" value="string" />
                  <el-option label="Boolean" value="boolean" />
                </el-select>
                <el-button icon="el-icon-delete" circle size="mini" @click="removeField(index)" />
              </div>
              <el-button icon="el-icon-plus" size="small" @click="addField">Add Field</el-button>
            </el-form-item>
            
            <el-form-item label="Timestamp">
              <el-date-picker
                v-model="writeForm.timestamp"
                type="datetime"
                placeholder="Select date and time (optional)"
                value-format="timestamp"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="writeData" :loading="writing">
                Write Data
              </el-button>
              <el-button @click="resetWriteForm">Reset</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="Export Data" name="export">
        <div class="export-panel">
          <h3>Export Query Results</h3>
          
          <el-form :model="exportForm" label-width="120px">
            <el-form-item label="Query">
              <el-input
                type="textarea"
                v-model="exportForm.query"
                :rows="5"
                placeholder="Enter your Flux query"
              />
            </el-form-item>
            
            <el-form-item label="Format">
              <el-radio-group v-model="exportForm.format">
                <el-radio label="csv">CSV</el-radio>
                <el-radio label="json">JSON</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="exportData" :loading="exporting">
                Export Data
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <el-dialog :title="dialogTitle" :visible.sync="showDialog" width="600px">
      <el-table :data="dialogData" max-height="400">
        <el-table-column prop="_value" :label="dialogTitle" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import influxdb from '@/utils/influxdb'
import Papa from 'papaparse'

export default {
  name: 'DataManagement',
  
  data() {
    return {
      activeTab: 'measurements',
      measurements: [],
      writeForm: {
        measurement: '',
        tags: [{ key: '', value: '' }],
        fields: [{ key: '', value: '', type: 'float' }],
        timestamp: null
      },
      exportForm: {
        query: '',
        format: 'csv'
      },
      writing: false,
      exporting: false,
      showDialog: false,
      dialogTitle: '',
      dialogData: []
    }
  },
  
  computed: {
    ...mapState(['currentConnection'])
  },
  
  mounted() {
    if (!this.currentConnection) {
      this.$message.warning('Please connect to a database first')
      this.$router.push('/connections')
      return
    }
    
    this.loadMeasurements()
  },
  
  methods: {
    ...mapActions(['loadMeasurements']),
    
    async loadMeasurements() {
      try {
        const measurements = await this.$store.dispatch('loadMeasurements')
        this.measurements = measurements
        this.$message.success('Measurements loaded successfully')
      } catch (error) {
        this.$message.error('Failed to load measurements: ' + error.message)
      }
    },
    
    async viewFields(measurement) {
      try {
        const fields = await influxdb.getFields(measurement)
        this.dialogTitle = `Fields in ${measurement}`
        this.dialogData = fields
        this.showDialog = true
      } catch (error) {
        this.$message.error('Failed to load fields: ' + error.message)
      }
    },
    
    async viewTags(measurement) {
      try {
        const tags = await influxdb.getTags(measurement)
        this.dialogTitle = `Tags in ${measurement}`
        this.dialogData = tags
        this.showDialog = true
      } catch (error) {
        this.$message.error('Failed to load tags: ' + error.message)
      }
    },
    
    addTag() {
      this.writeForm.tags.push({ key: '', value: '' })
    },
    
    removeTag(index) {
      this.writeForm.tags.splice(index, 1)
    },
    
    addField() {
      this.writeForm.fields.push({ key: '', value: '', type: 'float' })
    },
    
    removeField(index) {
      this.writeForm.fields.splice(index, 1)
    },
    
    async writeData() {
      if (!this.writeForm.measurement) {
        this.$message.warning('Please enter a measurement name')
        return
      }
      
      const validFields = this.writeForm.fields.filter(f => f.key && f.value)
      if (validFields.length === 0) {
        this.$message.warning('Please add at least one field')
        return
      }
      
      this.writing = true
      try {
        const tags = {}
        this.writeForm.tags.forEach(tag => {
          if (tag.key && tag.value) {
            tags[tag.key] = tag.value
          }
        })
        
        const fields = {}
        validFields.forEach(field => {
          let value = field.value
          switch (field.type) {
            case 'integer':
              value = parseInt(value)
              break
            case 'float':
              value = parseFloat(value)
              break
            case 'boolean':
              value = value.toLowerCase() === 'true'
              break
          }
          fields[field.key] = value
        })
        
        await influxdb.writeData(
          this.writeForm.measurement,
          tags,
          fields,
          this.writeForm.timestamp
        )
        
        this.$message.success('Data written successfully')
        this.resetWriteForm()
      } catch (error) {
        this.$message.error('Failed to write data: ' + error.message)
      } finally {
        this.writing = false
      }
    },
    
    resetWriteForm() {
      this.writeForm = {
        measurement: '',
        tags: [{ key: '', value: '' }],
        fields: [{ key: '', value: '', type: 'float' }],
        timestamp: null
      }
    },
    
    async exportData() {
      if (!this.exportForm.query) {
        this.$message.warning('Please enter a query')
        return
      }
      
      this.exporting = true
      try {
        const result = await influxdb.query(this.exportForm.query)
        
        if (result.length === 0) {
          this.$message.warning('Query returned no results')
          return
        }
        
        let content, filename, mimeType
        
        if (this.exportForm.format === 'csv') {
          content = Papa.unparse(result)
          filename = `export_${Date.now()}.csv`
          mimeType = 'text/csv'
        } else {
          content = JSON.stringify(result, null, 2)
          filename = `export_${Date.now()}.json`
          mimeType = 'application/json'
        }
        
        const blob = new Blob([content], { type: mimeType })
        const link = document.createElement('a')
        const url = URL.createObjectURL(blob)
        
        link.setAttribute('href', url)
        link.setAttribute('download', filename)
        link.style.visibility = 'hidden'
        
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        this.$message.success(`Data exported as ${this.exportForm.format.toUpperCase()}`)
      } catch (error) {
        this.$message.error('Export failed: ' + error.message)
      } finally {
        this.exporting = false
      }
    }
  }
}
</script>

<style scoped>
.data-management {
  padding: 20px;
  height: 100vh;
  overflow-y: auto;
}

.measurements-panel,
.write-panel,
.export-panel {
  background: white;
  padding: 20px;
  border-radius: 4px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h3 {
  margin: 0;
}

.tag-row,
.field-row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.write-panel h3,
.export-panel h3 {
  margin-bottom: 20px;
}
</style>